import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  Keyboard,
  Modal,
  ScrollView,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {
  LinearButton,
  TextButton,
  LinearBoardButton,
} from '../../components/Button';
import {NormalHeader} from '../../components/NavigationHeader';
import {showToast} from '../../components/Toast';
import {userLogout} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import ModalHandler from '../../components/ModalHandler';
import WalletUtils from '../../utils/wallet/WalletUtils';
import {queryWalltBalance} from '../../redux/action/index';
import {LinerBoardTextInput} from '../../components/TextInput';
//#FFCB26
class ConvertHT extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      swapType: 0,
      modalVisible: false,
      loading: false,
      password: '',
      htValue: '',
      swhtValue: '',
      gasUsed: 0,
      success: false,
      queryingGas: false,
    };
  }

  componentDidMount() {
    this.props.queryWalltBalance();
  }

  handlerConvert = () => {
    Keyboard.dismiss();
    this.setState(
      {
        loading: true,
      },
      async () => {
        console.log(this.state.password);
        console.log(this.state.htValue);

        try {
          var privateKey = await WalletUtils.privateKeyOfKeystore(
            this.props.userInfo.keystore,
            this.state.password,
          );
        } catch (err) {
          console.log('错误' + err);
          this.setState(
            {
              modalVisible: false,
              loading: false,
            },
            () => {
              this._showAlert({content: 'invalid password'});
            },
          );
          return;
        }
        let swht = this.props.coins.filter((item) => {
          return item.symbol == this.props.swapSymbol;
        })[0];

        // GAS 转 SWAP_GAS
        if (this.state.swapType == 0) {
          WalletUtils.transferSwapHt(
            privateKey,
            swht.contractAddress,
            this.state.htValue,
            (hash) => {
              console.log('交易已发送，正在监听交易->' + hash);
            },
          )
            .then((res) => {
              this.setState({
                success: true,
              });

              setTimeout(() => {
                this.setState(
                  {
                    modalVisible: false,
                    loading: false,
                  },
                  () => {
                    this.props.queryWalltBalance();
                    this.props.navigation.goBack();
                  },
                );
              }, 1000);
            })
            .catch((err) => {
              this.setState(
                {
                  modalVisible: false,
                  loading: false,
                },
                () => {
                  this._showAlert({content: 'failed,check your balance'});
                },
              );
            });
        } else {
          console.log('提现操作');
          WalletUtils.withdrawSWHT(
            privateKey,
            swht.contractAddress,
            this.props.userInfo.address,
            this.state.htValue,
            (hash) => {
              this.setState({
                result: '交易已发送，正在监听交易->' + hash,
              });
            },
          )
            .then((res) => {
              this.setState({
                success: true,
              });

              setTimeout(() => {
                this.setState(
                  {
                    modalVisible: false,
                    loading: false,
                  },
                  () => {
                    this.props.queryWalltBalance();
                    this.props.navigation.goBack();
                  },
                );
              }, 1000);
            })
            .catch((err) => {
              this.setState(
                {
                  modalVisible: false,
                  loading: false,
                },
                () => {
                  this._showAlert({content: 'failed,check your balance'});
                },
              );
            });
        }
      },
    );
  };

  _handlerView = () => {
    return (
      <View style={{width: '100%'}}>
        <Text
          style={{
            fontWeight: 'bold',
            marginTop: 20,
            marginBottom: 20,
            color: '#6902F4',
            fontSize: 20,
          }}>
          Confirm your transcation
        </Text>
        <Image
          style={{height: 1, width: '100%', marginBottom: 20}}
          source={require('../../assets/auction/line.png')}></Image>
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            marginBottom: 10,
          }}>
          <Text style={{color: '#6902F4'}}>Transfer Amount</Text>
          <Text style={{color: '#6902F4'}}>{`${this.state.htValue}${
            this.state.swapType ? this.props.swapSymbol : this.props.gasSymbol
          }`}</Text>
        </View>
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            marginBottom: 20,
          }}>
          <Text style={{color: '#6902F4'}}>Gas Fee</Text>
          <Text
            style={{
              color: '#6902F4',
            }}>{`${this.state.gasUsed}${this.props.gasSymbol}`}</Text>
        </View>
        <LinerBoardTextInput
          style={{
            width: '100%',
            padding: 0,
            height: 44,
          }}
          secureTextEntry={true}
          onChangeText={(text) => {
            this.setState({
              password: text,
            });
          }}
          placeholder="Your wallet password"></LinerBoardTextInput>
        <View
          style={{
            width: '100%',
            flexDirection: 'row',
            justifyContent: 'flex-end',
            marginBottom: 30,
          }}>
          <LinearBoardButton
            buttonStyle={{
              width: 100,
              height: 30,
              marginRight: 20,
            }}
            onPress={() => {
              this.setState({
                modalVisible: false,
              });
            }}
            text={'Cancel'}></LinearBoardButton>
          <LinearButton
            buttonStyle={{
              width: 100,
              height: 30,
            }}
            onPress={this.handlerConvert}
            text={'Confirm'}></LinearButton>
        </View>
      </View>
    );
  };

  onPressBackground = () => {
    if (this.state.loading) {
      return;
    }

    this.setState({
      modalVisible: false,
      loading: false,
    });
  };

  renderComponent = () => {
    let {
      swapType,
      modalVisible,
      loading,
      success,
      htValue,
      swhtValue,
      queryingGas,
    } = this.state;
    let {coins} = this.props;

    let swht =
      coins.length > 0
        ? coins.filter((item) => item.symbol == this.props.swapSymbol)[0]
        : {};
    let ht =
      coins.length > 0
        ? coins.filter((item) => item.symbol == this.props.gasSymbol)[0]
        : {};

    return (
      <View style={{flex: 1, backgroundColor: '#160231'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Convert"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />
        <ScrollView
          scrollEnabled={false}
          keyboardDismissMode
          style={{padding: 20, flex: 1}}>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: 20,
            }}>
            <Text style={{fontWeight: 'bold', fontSize: 20, color: 'white'}}>
              From
            </Text>
            {swapType == 1 ? (
              <Text style={{color: 'white'}}>{`Balance: ${
                swht.balance + this.props.swapSymbol
              }`}</Text>
            ) : (
              <Text style={{color: 'white'}}>{`Balance: ${
                ht.balance + this.props.gasSymbol
              }`}</Text>
            )}
          </View>
          <LinerBoardTextInput
            style={{
              width: '100%',
              padding: 0,
              height: 44,
            }}
            keyboardType={'numeric'}
            onChangeText={(text) => {
              console.log('change' + text);
              this.setState({
                htValue: text,
                swhtValue: text,
              });
            }}
            suffix={
              swapType == 1 ? this.props.swapSymbol : this.props.gasSymbol
            }
            placeholder="0.00"></LinerBoardTextInput>
          <TouchableOpacity
            activeOpacity={0.8}
            style={{alignSelf: 'center', margin: 20}}
            onPress={() => {
              this.setState({
                swapType: !this.state.swapType,
              });
            }}>
            <Image
              style={{width: 50, height: 50}}
              source={require('../../assets/user/icon_switch.png')}
            />
          </TouchableOpacity>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              marginBottom: 20,
              alignItems: 'center',
            }}>
            <Text style={{fontWeight: 'bold', fontSize: 20, color: 'white'}}>
              To
            </Text>
            <Text>
              {swapType == 1 ? (
                <Text style={{color: 'white'}}>{`Balance: ${
                  ht.balance + this.props.gasSymbol
                }`}</Text>
              ) : (
                <Text style={{color: 'white'}}>{`Balance: ${
                  swht.balance + this.props.swapSymbol
                }`}</Text>
              )}
            </Text>
          </View>
          <LinerBoardTextInput
            editable={false}
            style={{
              width: '100%',
              padding: 0,
              height: 44,
            }}
            suffix={
              swapType == 1 ? this.props.gasSymbol : this.props.swapSymbol
            }
            value={swapType == 0 ? swhtValue : htValue}
            placeholder="0.00"></LinerBoardTextInput>
          <Text style={{marginTop: 20, alignSelf: 'center', color: 'white'}}>
            {`1 ${this.props.swapSymbol} = 1 ${this.props.gasSymbol}`}
          </Text>
        </ScrollView>
        <LinearButton
          text={'Convert'}
          loading={queryingGas}
          onPress={() => {
            console.log(parseFloat(htValue));

            //检查余额
            if (isNaN(parseFloat(htValue)) || parseFloat(htValue) == 0) {
              this._showAlert({content: 'Insufficient Balance'});
              return;
            }
            if (swapType == 0 && parseFloat(htValue) > ht.balance) {
              this._showAlert({content: 'Insufficient Balance'});
              return;
            }
            if (swapType == 1 && parseFloat(swhtValue) > swht.balance) {
              this._showAlert({content: 'Insufficient Balance'});
              return;
            }
            console.log('获取gas');

            this.setState({
              queryingGas: true,
            });

            WalletUtils.getSwapTxGasPrice()
              .then((res) => {
                this.setState({
                  queryingGas: false,
                  gasUsed: res,
                  modalVisible: true,
                });
              })
              .catch((err) => {
                console.log('获取失败');
              });
          }}
          buttonStyle={{
            alignSelf: 'center',
            width: 150,
            marginBottom: 30,
          }}></LinearButton>
        <View
          style={{
            width: '100%',
            height: this.props.widgetLayout.show
              ? this.props.widgetLayout.height
              : 0,
            marginTop: 10,
          }}></View>
        <ModalHandler
          visible={modalVisible}
          loading={loading}
          success={success}
          handlerView={this._handlerView}
          onPressBackground={this.onPressBackground}
        />
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  coins: state.Chain.coins,
  gasSymbol: state.Chain.gasSymbol,
  swapSymbol: state.Chain.swapSymbol,
  widgetLayout: state.Layout.widgetLayout,
});

const mapDispatchToProps = (dispatch) => ({
  queryWalltBalance: () => dispatch(queryWalltBalance()),
});

export default connect(mapStateToProps, mapDispatchToProps)(ConvertHT);
